package com.ly.mpayment.rest.up.chongqing;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

@Component
@Path("chongqing")
public class ChongQingRest {
	static Logger logger = Logger.getLogger(ChongQingRest.class);


	@Autowired
	IUporderService upOrderService;

	@Autowired
	IDownRechargeFlowService flowService;

	@Autowired
	IDownShopInfoService shopService;



	/**
	 * 增加签名
	 * outOrderSn	商户订单号	是	2016100110390994
	 * resultCode	状态值	是	状态含义：
	 *       23-待备货(号卡专有，订购号码见extendParam)
	 *       25-已发货(号卡专有，物流见extendParam)
	 * 30-办理成功
	 * 31-激活成功(号卡专有，号码见extendParam)
	 * 40-办理失败
	 * 41-激活失败(号卡专有)
	 * 其它-异常状态，需手动核实
	 * resultMsg	状态说明	是	状态文本
	 * extendParam	扩展参数	是	{
	 * 'serial':“流水号”,//话费产品专有
	 * 'bookPhone'：“订购的号码”,//号卡产品专有
	 * 'activeStatus'：“是否激活”,//0-否，1-是，号卡专有
	 * 'chargeStatus'：“是否充值”,//0-否，1-是，号卡专有
	 * 'expressNumber'：“物流单号”,//号卡已发货时有
	 * 'expressCompany'：“物流公司”,//号卡已发货时有
	 * }
	 * sign	签名	是	签名规则见 签名算法
	 * @param data
	 * @return
	 */
	@SuppressWarnings("-access")
	@POST
	@Path("callBack")
	public synchronized String callBack(String data){
		logger.info("chongqing_callBack:"+data);
		if(!StringUtils.isBlank(data)){
			try {
				JSONObject json = JSONObject.parseObject(data);

				UpOrder order = upOrderService.findById(json.getString("outOrderSn"));
				if(json.getString("resultCode").equals("30") && order != null && order.getStatus() == Config.status[0]){
					order.setRemark(json.containsKey("extendParam") ? json.getJSONObject("extendParam").getString("serial") : json.getString("resultMsg"));
					RechargeRest.successUpOrder.add(order);
				}else if(json.getString("resultCode").equals("40")  && order != null && order.getStatus() == Config.status[0]){
					order.setRemark(json.getString("resultMsg"));
					RechargeRest.failtUpOrder.add(order);
				}else{
					logger.info("chongqing_not_found_order:"+data);
				}
				return "success";
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "fail";
	}

	public void commitOrder(UpOrder order, UpShopInfo shop) {
		try {
			UpOrder product = upOrderService.findOrderProduct(order.getUporderuuid());
			if (product != null) {
				JSONObject data = new JSONObject();
				data.put("username",shop.getAppId());
				data.put("chargeAccount",order.getUpphonenum());
				data.put("outOrderSn",order.getUporderuuid());
				data.put("goodsCode",order.getUpShopPro().getProductCode());
				data.put("timestamp",System.currentTimeMillis() / 1000);
				data.put("extendParam","");
				data.put("sign",MD5.md5(StringSort.doSign(data).concat("&apikey=").concat(shop.getUpkey())));
				String result = HttpClient.post(shop.getOrderCommitAddress(),data.toJSONString());
				logger.info("commitchongqing_result:" + result+",data:"+data.toJSONString());
				if (!StringUtils.isBlank(result)) {
					try{
						JSONObject json = JSONObject.parseObject(result);
						if(json.getString("code").equals("00")){
							this.upOrderService.updateUpOrderMsg(order, json.getString("msg"),json.getString("msg"));
						}else if (json.getString("code").startsWith("1") || json.getString("code").startsWith("2")
						|| json.getString("code").startsWith("5") ) {
							order.setRemark(json.getString("msg"));
							RechargeRest.failtUpOrder.add(order);
						}
					}catch (Exception e){
						e.printStackTrace();
						upOrderService.updateUpOrderArtificial(order, "","提单失败:");
					}
				} else {
					this.upOrderService.updateUpOrderMsg(order, "", Config.commitFailt);
					logger.info("commitchongqing_error" + order.getUpphonenum());
				}
			}else{
				logger.info("commitchongqing error not found product" + order.getUporderuuid());
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage());
			this.upOrderService.updateUpOrderMsg(order, "", Config.commitFailt);
			logger.info("commitchongqing_error+" + order.getUpphonenum());
		}
	}

	/**
	 * username	用户名	是	cszh
	 * outOrderSn	提交时的商户订单号	是	202008211304114
	 * timestamp	当前时间戳	是	10位数字，示例1479456614，允许3分钟误差
	 * 订单查询
	 * @param upOrder
	 * @param shopInfo
	 */
	public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
		JSONObject data = new JSONObject();
		data.put("username",shopInfo.getAppId());
		data.put("outOrderSn",upOrder.getUporderuuid());
		data.put("timestamp",System.currentTimeMillis() / 1000);
		data.put("sign",MD5.md5(StringSort.doSign(data).concat("&apikey=").concat(shopInfo.getUpkey())));
		String result = HttpClient.post(shopInfo.getOrderStatusAddress(),data.toJSONString());
		logger.info("chongqing_queryReport:"+result);
		if(result != null){
			//状态含义：
			//10-待处理
			//20-处理中
			//30-办理成功
			//40-办理失败
			//其它-异常状态，需手动核实

			JSONObject json = JSONObject.parseObject(result);
			if(json.getString("code").equals("00")){
				UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
				if(json.getInteger("resultCode").equals(30) && order != null && order.getStatus() == Config.status[0]){
					order.setRemark(json.containsKey("serial") ? json.getString("serial") : json.getString("resultMsg"));
					RechargeRest.successUpOrder.add(order);
				}else if( (json.getInteger("resultCode").equals("40")) && order != null && order.getStatus() == Config.status[0]){
					order.setRemark(json.getString("Status"));
					RechargeRest.failtUpOrder.add(order);
				}
			}
		}else{
			logger.info("chongqing order failt:"+upOrder.getUpphonenum());
		}
	}


}
